﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Rule
{
    public class SubImageTemplateRule : TemplateRule
    {
        private string image;

        public string Image
        {
            get { return image; }
            set { image = value; }
        }

        private float threshold = 0.9f;

        public float Threshold
        {
            get { return threshold; }
            set { threshold = value; }
        }

        public override bool parseFromXmlNode(System.Xml.XmlNode node)
        {
            if (node == null)
                return false;

            XmlAttribute imageAttr = node.Attributes["image"];
            XmlAttribute thresholdAttr = node.Attributes["threshold"];

            if (imageAttr == null)
            {
                Debug.WriteLine("子图片名称存在。");
                return false;
            }

            if (thresholdAttr == null)
            {
                Debug.WriteLine("阈值未指定，使用默认值。");
            }

            if (imageAttr == null && string.IsNullOrEmpty(imageAttr.Value))
            {
                Debug.WriteLine("子图片名称不能为空值。");
                return false;
            }
            else
            {
                image = imageAttr.Value;
            }

            if (thresholdAttr != null && !float.TryParse(thresholdAttr.Value, out threshold))
            {
                Debug.WriteLine("用户指定了阈值但该值不合法。");
                return false;
            }

            return true;
        }

        public override string ToString()
        {
            return string.Format("Image: {0}, Threshold: {1}", image, threshold);
        }

        public override bool match(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                return false;

            double value = 0.0;

            bool res = MatchTemplate(image, fileName, ref value);

            return value > threshold;
        }

        [DllImport("DocRec.dll", EntryPoint = "MatchTemplate")]
        public static extern bool MatchTemplate([MarshalAs(UnmanagedType.LPStr)] string objectName,
            [MarshalAs(UnmanagedType.LPStr)] string sceneName, ref double value);
    }
}
